const app = getApp();
// import md5 from "../../miniprogram_npm/js-md5/index"

Page({
  options: {
    styleIsolation: "shared",
  },
  data: {
    role: 1,
    mobile: "",
    verification: "",
    showPicker: false,
    disabled: false,
    downtime: 60000,
    checked: true,
    roleList: [{
        id: 1,
        text: "交易中心"
      },
      {
        id: 2,
        text: "种植户"
      },
      {
        id: 3,
        text: "小工"
      }
    ],
    roleMap: {
      1: "交易中心",
      2: "种植户",
      3: "小工"
    }
  },
  onLoad: function (options) {
    if (options && options.role) {
      this.setData({
        role: options.role
      });
    }
    if (app.globalData.userInfo && app.globalData.userInfo.role) {
      app.switchTabWithRole(app.globalData.userInfo.role);
      return
    } else if (options && options.token) {
      wx.setStorageSync("token", options.token);
      this.fromLogin()
    }
  },
  onChange(event) {
    this.setData({
      checked: event.detail
    });
  },
  onConfirm(event) {
    const {
      value
    } = event.detail;
    this.setData({
      role: value.id,
      showPicker: false
    });
  },
  onCancel() {
    this.setData({
      showPicker: false
    });
  },
  pickerRole() {
    this.setData({
      showPicker: true
    });
  },
  fromLogin() {
    let role = 2;
    wx.showLoading({
      title: "正在登录"
    });
    this.getMarketUserMyInfo().then((markets) => {
      if (markets && markets.length) {
        // 目前没有切交易市场权限页面,只能默认选中第一个
        let market = markets[0];
        let Index = market.marketRoles && market.marketRoles.findIndex((item) => item.marketRoleId == role);
        if (Index === null || Index === -1) {
          wx.showToast({
            icon: "none",
            title: "该账号无登录权限"
          });
          return false;
        }
        this.getMyInfo(market);
      } else {
        wx.clearStorage({
          success: () => {
            let app = getApp();
            app.globalData = {};
            wx.showToast({
              icon: "none",
              title: "该账号无登录权限"
            });
          }
        });
        return false;
      }
    });
  },
  login() {
    const {
      mobile,
      verification,
      checked
    } = this.data;
    if (!mobile) {
      wx.showToast({
        title: "请输入手机号",
        icon: "none",
        duration: 2000
      });
      return;
    } else if (!checked) {
      wx.showToast({
        title: "请先同意用户协议",
        icon: "none",
        duration: 2000
      });
      return;
    } else if (!verification) {
      wx.showToast({
        title: "请输入验证码",
        icon: "none",
        duration: 2000
      });
      return;
    }
    wx.showLoading({
      title: "正在登录"
    });
    wx.$apis
      .login({
        mobile,
        verification
      })
      .then((res) => {
        if (res.data) {
          const {
            token_type,
            access_token
          } = res.data;
          wx.setStorageSync("token", token_type + " " + access_token);
          const role = this.data.role;
          // 17665015296 叶红伟
          wx.showLoading({
            title: "正在登录"
          });
          this.getMarketUserMyInfo().then((markets) => {
            if (markets && markets.length) {
              // 目前没有切交易市场权限页面,只能默认选中第一个
              let market = markets[0];
              let Index = market.marketRoles && market.marketRoles.findIndex((item) => item.marketRoleId == role);
              if (Index === null || Index === -1) {
                wx.showToast({
                  icon: "none",
                  title: "该账号无登录权限"
                });
                return false;
              }
              this.getMyInfo(market);
            } else {
              wx.clearStorage({
                success: () => {
                  let app = getApp();
                  app.globalData = {};
                  wx.showToast({
                    icon: "none",
                    title: "该账号无登录权限"
                  });
                }
              });
              return false;
            }
          });
        }
      });
  },

  // 查看我的全部交易市场用户详细信息
  getMarketUserMyInfo() {
    return new Promise((resolve, reject) => {
      wx.$apis
        .getMyUserInfo()
        .then((res) => {
          resolve(res.data);
        })
        .catch((err) => {
          reject(err);
        });
    });
  },

  getMyInfo(market) {
    const role = this.data.role;
    const roleName = this.data.roleMap[role];
    wx.showLoading({
      title: "正在登录"
    });
    wx.$apis.getMyInfo().then((res) => {
      let userDetail = {
        ...res.data
      };
      delete userDetail.companyList;
      let companyList = res.data.companyList || [];
      if (companyList && companyList.length) {
        let Index = companyList.findIndex((item) => item.companyId === market.companyId);
        if (Index < 0) {
          wx.clearStorage({
            success: () => {
              let app = getApp();
              app.globalData = {};
              wx.showToast({
                icon: "none",
                title: "该账号无交易市场登录权限"
              });
            }
          });
          return false;
        }
        let companyData = companyList[Index];
        let userInfo = {
          roleName: roleName,
          role: role,
          userDetail: userDetail,
          companyList: companyList,
          companyData: companyData
        };
        wx.setStorageSync("userInfo", JSON.stringify(userInfo));
        app.globalData.userInfo = userInfo;
        app.switchTabWithRole(role);
      } else {
        wx.showToast({
          title: "暂无此身份，请尝试其他身份登录",
          icon: "none",
          duration: 2000
        });
      }
    });
  },
  toRegister() {
    wx.navigateTo({
      url: "/pages/register/index"
    });
  },
  toPrivacy() {
    wx.navigateTo({
      url: "/pages/privacy/index"
    });
  },
  sendMsg() {
    if (!this.data.mobile) {
      wx.showToast({
        title: "请输入手机号",
        icon: "none",
        duration: 2000
      });
      return;
    }
    wx.showLoading({
      title: "发送短信中"
    });
    wx.$apis.sendSms(this.data.mobile, 0).then((res) => {
      wx.showToast({
        title: res.data,
        icon: "none",
        duration: 2000
      });
      this.setData({
        disabled: true
      });
      const countDown = this.selectComponent(".control-count-down");
      countDown.start();
    });
  },
  finished() {
    this.setData({
      disabled: false,
      downtime: 60000
    });
  }
});